package cn.fengtang.chatglm.data.trigger.http;

import cn.fengtang.chatglm.data.domain.model.aggregates.ChatProcessAggregate;
import cn.fengtang.chatglm.data.domain.model.entity.PromptEntity;
import cn.fengtang.chatglm.data.domain.service.IChatService;
import cn.fengtang.chatglm.data.trigger.http.dto.ChatGLMRequestDTO;
import cn.fengtang.chatglm.model.ChatCompletionRequest;
import cn.fengtang.data.types.exception.ChatGLMException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

@Slf4j
@RestController()
@CrossOrigin("${app.config.cross-origin}")
@RequestMapping("/api/${app.config.api-version}")
public class ChatGLMServiceController {

    @Resource
    private IChatService chatService;

    /**
     * 流式问题，ChatGPT 请求接口
     * <p>
     * curl -X POST \
     * http://localhost:8090/api/v1/chat/completions \
     * -H 'Content-Type: application/json;charset=utf-8' \
     * -H 'Authorization: access' \
     * -d '{
     * "messages": [
     * {
     * "content": "小傅哥是谁",
     * "role": "user"
     * }
     * ],
     * "model": "glm-4v"
     * }'
     */
    @RequestMapping(value = "chat/completions", method = RequestMethod.POST)
    public ResponseBodyEmitter completionsStream(
            @RequestBody ChatGLMRequestDTO request
            , @RequestHeader("Authorization") String token
            , HttpServletResponse response) {

        try {
            // 1. 基础配置；流式输出、编码、禁用缓存
            response.setContentType("text/event-stream");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Cache-Control", "no-cache");

            // 2. 构建参数
            ChatProcessAggregate chatProcessAggregate = ChatProcessAggregate.builder()
                    .token(token)
                    .model(request.getModel())
                    .stream(request.getStream())
                    .isCompatible(request.getIsCompatible())
                    .messages(request.getMessages().stream()
                            .map(prompt -> PromptEntity.builder()
                                    .role(prompt.getRole())
                                    .content(prompt.getContent())
                                    .build())
                            .collect(Collectors.toList()))
                    .build();

            // 3. 请求结果&返回
            return chatService.completions(chatProcessAggregate);
        } catch (Exception e) {
            log.error("流式应答，请求模型：{}发生异常", request.getModel(), e);
            throw new ChatGLMException(e.getMessage());
        }

    }
}
